﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YBApproval.IDAL;
using YBApproval.Model;
using System.Data;

namespace YBApproval.EFDAL
{
    public class RoleDAL : IRole
    {
        private YBDbContext _db = new YBDbContext();

        public List<Role> GetUserRoleList(List<int> roleIds)
        {            
            try
            {
                if (roleIds!=null && roleIds.Count > 0)
                {
                    List<Model.Role> roles = new List<Model.Role>();
                    foreach (var id in roleIds)
                    {
                        roles.Add(_db.Roles.SingleOrDefault(r => r.Id == id));
                    }
                    return roles;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }


        public List<Role> GetAll()
        {
            try
            {
                //List<Role> roles = _db.Roles.Where(r => r.IsActive == true).ToList();
                List<Role> roles = _db.Roles.Where(r=>r.IsActive).ToList();
                return roles;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public int InsertNewRole(Role newRole)
        {
            try
            {
                Role newR = new Role();
                newR.CreateDt = newRole.CreateDt;
                newR.Desc = newRole.Desc;
                newR.IsActive = newRole.IsActive;
                newR.LastUpdatedBy = newRole.LastUpdatedBy;
                newR.LastUpdatedDt = newRole.LastUpdatedDt;
                newR.Name = newRole.Name;

                _db.Roles.Add(newR);
                _db.SaveChanges();
                return newR.Id;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        public int DeleteRoleById(int rId)
        {
            try
            {
                Role delRole = _db.Roles.SingleOrDefault(u => u.Id == rId);
                if (delRole != null)
                {
                    delRole.IsActive = false;
                    //_db.Roles.Remove(delRole);
                    _db.Entry(delRole).State = EntityState.Modified;
                    _db.SaveChanges();
                return 1;
                } 
                else
                {
                    return 0;
                }
            }
            catch (Exception)
            {
                return -1;
            }
        }

        public void Dispose()
        {
            _db.Dispose();
        }


    }
}

